// 直播相关动画
import _$animation from "./animation.js";
// 创建动画对象
function createAnimation(queue, name, prefix, time, length, end, start = 0) {
	// 添加动画
	var names = [];
	for (var num = start; num <= end; num++) {
		names.push(prefix + '0'.repeat(Math.max(length - String(num).length, 0)) + num);
	}
	var imgs = [];
	names.forEach(item => {
		require(['@/assets/img/' + item + '.png'], function(path) {
			imgs.push(path);
			if (imgs.length >= names.length) {
				var div = document.createElement('div');
				_$animation.attr(div, {
					'class': name + '-animation live-animation'
				});
				var _animation = _$animation.$animation(div, {
					sequence: {
						imgs: imgs,
						time: time
					}
				});
				queue.push(_animation);
				_animation.on('play', function() {
					console.info(audioPaly.play(name))
					audioPaly && audioPaly.play(name);
				});
				_animation.on('stop', function() {
					document.body.removeChild(this.element);
				});
			}
		});
	});
}
//加载音乐
var audioPaly = null;
(function(loadAudio) {
	var loaded = 0,
		loadAudioData = {};
	loadAudio.forEach((url) => {
		var key = url.match(/\w+$/)[0];
		loadAudioData[key] = {
			urls: []
		}
		require(['@/assets/media/' + url + '.ogg', '@/assets/media/' + url + '.mp3', '@/assets/media/' + url + '.wav'],
			function(ogg, mp3, wav) {
				loadAudioData[key].urls.push(ogg, mp3, wav);
				loaded++;
				if (loaded >= loadAudio.length) {
					audioPaly = _$animation.$audioPaly(loadAudioData);
				}
			});
	});
})([
	'live/ferrari',
]);

// 法拉利
var ferraris = [];
createAnimation(ferraris, 'ferrari', 'live/animation/ferrari/F_', 4, 2, 59, 1);
// 火箭
var rockets = [];
createAnimation(rockets, 'rocket', 'live/animation/rocket/H_', 4, 2, 60, 1);
// 玫瑰
var roses = [];
createAnimation(roses, 'rose', 'live/animation/rose/M_', 4, 5, 59, 0);

// 播放动画和音乐
function playAnimation($animations) {
	var $animation = null;
	for (var key = 0; key < $animations.length; key++) {
		if ($animations[key].getStatus() === 'stop') {
			$animation = $animations[key];
			break;
		}
	}
	if (!$animation && $animations[0]) {
		$animations.push($animation = $animations[0].clone($animation.element.cloneNode(), true));
	}
	if (!$animation) {
		return false;
	}
	if ($animation.element.parentNode !== document.body) {
		document.body.appendChild($animation.element);
	}
	if (_$animation.$Animation.getStatus() !== 'play') {
		_$animation.$Animation.play();
	}
	return $animation.play(null, false, false);
}

export default {
	ferrari: function() {
		playAnimation(ferraris);
	},
	rocket: function() {
		playAnimation(rockets);
	},
	rose: function() {
		playAnimation(roses);
	}
};
